package projectmanagement.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.validation.Errors;

import projectmanagement.model.Task;

public class EnterTaskValidator implements
		org.springframework.validation.Validator {

	public boolean supports(Class clazz) {
		return clazz.equals(Task.class);
	}

	public void validate(Object command, Errors errors) {
		Task task = (Task) command;
		if (task == null)
			return;

		String header = task.getHeader();
		String comment = task.getComment();

		if (header == null || header.trim().length() == 0) {
			errors.reject("error.task.header.required");
		}
		
		if (checkSymbols(header) || checkSymbols(comment)){
			errors.reject("error.task.illegal.character");
		}

		String deadlineDate = task.getDeadlineDateStr();
		if (deadlineDate != null && validDate(task.getDeadlineDateStr())) {
			errors.reject("error.task.invalid.date");
		}
	}

	private boolean validDate(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date testDate = null;

		try {
			testDate = sdf.parse(date);
		} catch (ParseException e) {
			return false;
		}

		if (!sdf.format(testDate).equals(date)) {
			return false;
		}
		return true;
	}
	
	private boolean checkSymbols(String s){
		if(s.contains(">") || s.contains("<") || s.contains("javascript")){
			return true;
		}
		return false;
	}
}
